<?php

namespace app\modules\backend\controllers;

use app\models\User;
use app\models\Task;
use app\models\Area;
use app\models\Repair;
use app\models\RepairEvaluate;
use app\models\TaskRepair;
use app\models\Device;
use app\tools\Re;
use app\tools\JPushHelper;
use Yii;

class RepairController extends BaseController
{
  public $task_state_arr = ['等待接单', '已接单', '已完成', '已评价', '已取消'];
  public $repair_state_arr = ['', '已接单', '已出发', '已到达', '维修取消', '维修中', '维修完成', '已评价'];

  public function actionListForSelect(){
      $list = Repair::find()->where(['type' => [1,3], 'status' => 1])->select('id, name')->all();
      return Re::data(['data' => $list]);
  }

  public function actionTaskList(){
      $content = Yii::$app->request->post('content', '');
      $page = Yii::$app->request->post('page', 0);
      $query = Task::find()->where(['status' => [0,1]]);
      if (!empty($content)) {
          $query->andWhere(['like', 'content', $content]);
      }
      $task_list = $query->orderBy('created_at desc')->limit(Task::PAGE_SIZE)->offset(Task::PAGE_SIZE*$page)->all();
      $task_data = [];
      if ($task_list) {
        foreach ($task_list as $v) {
          $state = $v->state;
          if (!$state && ($v->created_at + 900) < time()) {
            $state = -1;
          }
          $task_data[] = [
            'id' => $v->id,
            'user_name' => $v->user_name,
            'area_name' => $v->province.$v->city.$v->area,
            'content' => mb_substr($v->content, 0, 50).'...',
            'state' => $state,
            'state_name' => $state == -1 ? '已超时' : $this->task_state_arr[$state],
            'is_over' => $state == -1 ? 1 : 0,
            'created_time' => date('Y-m-d H:i', $v->created_at)
          ];
        }
      }
      return Re::data([
          'data' => $task_data,
          'totalPage' => $query->count(),
          'currentPage' => $page,
          'perPage' => Task::PAGE_SIZE
      ]);
  }

  public function actionChangeTaskStatus(){
      $id = Yii::$app->request->post('id', 0);
      $status = Yii::$app->request->post('status', 0);
      $task_info = Task::findOne($id);
      if (!$task_info) {
          return Re::data(null, '任务信息读取失败', Re::ERROR);
      }
      $task_info->status = $status;
      $task_info->save();
      return Re::data();
  }

  public function actionRepairList(){
      $name = Yii::$app->request->post('name', '');
      $page = Yii::$app->request->post('page', 0);
      $query = Repair::find()->where(['type' => 1, 'status' => [0,1]]);
      if (!empty($name)) {
          $query->andWhere(['like', 'name', $name]);
      }
      $repair_list = $query->orderBy('created_at desc')->limit(Repair::PAGE_SIZE)->offset(Repair::PAGE_SIZE*$page)->all();
      $repair_data = [];
      if ($repair_list) {
        foreach ($repair_list as $v) {
          $city_value = [];
          array_push($city_value, $v->area->parentArea->parentArea->id, $v->area->parentArea->id, $v->area->id);
          $repair_data[] = [
            'id' => $v->id,
            'name' => $v->name,
            'area_name' => $v->area->parentArea->parentArea->name.$v->area->parentArea->name.$v->area->name,
            'area_id' => $v->area_id,
            'city_value' => $city_value,
            'star_avg' => $v->star_avg,
            'created_time' => date('Y-m-d H:i', $v->created_at)
          ];
        }
      }
      return Re::data([
          'data' => $repair_data,
          'totalPage' => $query->count(),
          'currentPage' => $page,
          'perPage' => Repair::PAGE_SIZE
      ]);
  }

  public function actionEditRepair(){
      $id = Yii::$app->request->post('id', 0);
      $post = Yii::$app->request->post();
      return $this->edit(Repair::class, $id, $post);
  }

  public function actionRepairUserList(){
    $repair_id = Yii::$app->request->post('repair_id', 0);
    $phone = Yii::$app->request->post('phone', '');
    $page = Yii::$app->request->post('page', 0);
    $query = User::find()->where(['status' => 1, 'repair_id' => $repair_id]);
    if (!empty($phone)) {
        $query->andWhere(['like', 'phone', $phone]);
    }
    $user_list = $query->orderBy('created_at desc')->limit(User::PAGE_SIZE)->offset(User::PAGE_SIZE*$page)->all();
    $user_data = [];
    if ($user_list) {
      foreach ($user_list as $v) {
        $user_data[] = [
          'id' => $v->id,
          'phone' => $v->phone,
          'name' => $v->name,
          'status' => $v->status,
          'created_time' => date("Y-m-d H:i", $v->created_at),
        ];
      }
    }
    return Re::data([
        'data' => $user_data,
        'totalPage' => $query->count(),
        'currentPage' => $page,
        'perPage' => User::PAGE_SIZE
    ]);
  }

  public function actionRepairEvaluateList(){
    $repair_id = Yii::$app->request->post('repair_id', 0);
    $page = Yii::$app->request->post('page', 0);
    $query = RepairEvaluate::find()->where(['status' => 1]);
    if (!empty($repair_id)) {
        $query->andWhere(['repair_id' => $repair_id]);
    }
    $evaluate_list = $query->orderBy('created_at desc')->limit(RepairEvaluate::PAGE_SIZE)->offset(RepairEvaluate::PAGE_SIZE*$page)->all();
    $evaluate_data = [];
    if ($evaluate_list) {
      foreach ($evaluate_list as $v) {
        $evaluate_data[] = [
          'id' => $v->id,
          'star_finsh_time' => $v->star_finsh_time,
          'star_finsh_quality' => $v->star_finsh_quality,
          'star_service' => $v->star_service,
          'content' => $v->content,
          'repair_name' => $v->repair->name,
          'task_name' => $v->task->name,
          'user_name' => $v->user->name,
          'status' => $v->status,
          'created_time' => date("Y-m-d H:i", $v->created_at),
        ];
      }
    }
    return Re::data([
        'data' => $evaluate_data,
        'totalPage' => $query->count(),
        'currentPage' => $page,
        'perPage' => RepairEvaluate::PAGE_SIZE
    ]);
  }

  public function actionChangeRepairEvaluateStatus(){
      $id = Yii::$app->request->post('id', 0);
      $status = Yii::$app->request->post('status', 0);
      $evaluate_info = RepairEvaluate::findOne($id);
      if (!$evaluate_info) {
          return Re::data(null, '评价信息读取失败', Re::ERROR);
      }
      $evaluate_info->status = $status;
      $evaluate_info->save();
      return Re::data();
  }

  public function actionTaskRepairList(){
    $repair_id = Yii::$app->request->post('repair_id', 0);
    $page = Yii::$app->request->post('page', 0);
    $query = TaskRepair::find()->where(['status' => 1]);
    if (!empty($repair_id)) {
        $query->andWhere(['repair_id' => $repair_id]);
    }
    $task_repair_list = $query->orderBy('created_at desc')->limit(TaskRepair::PAGE_SIZE)->offset(TaskRepair::PAGE_SIZE*$page)->all();
    $task_repair_data = [];
    if ($task_repair_list) {
      foreach ($task_repair_list as $v) {
        $task_repair_data[] = [
          'id' => $v->id,
          'repair_name' => $v->repair->name,
          'task_content' => $v->task->content,
          'repair_user_id' => $v->user_id,
          'repair_user_name' => $v->user->phone,
          'user_name' => $v->task->user->name,
          'state' => $v->state,
          'state_name' => $this->repair_state_arr[$v->state],
          'status' => $v->status,
          'created_time' => date("Y-m-d H:i", $v->created_at),
        ];
      }
    }
    return Re::data([
        'data' => $task_repair_data,
        'totalPage' => $query->count(),
        'currentPage' => $page,
        'perPage' => TaskRepair::PAGE_SIZE
    ]);
  }

  public function actionChangeTaskRepairStatus(){
      $id = Yii::$app->request->post('id', 0);
      $status = Yii::$app->request->post('status', 0);
      $task_repair_info = TaskRepair::findOne($id);
      if (!$task_repair_info) {
          return Re::data(null, '抢修订单信息读取失败', Re::ERROR);
      }
      $task_repair_info->status = $status;
      $task_repair_info->save();
      return Re::data();
  }

  public function actionCancelTaskRepair(){
    $id = Yii::$app->request->post('id', 0);
    $taskRepair = TaskRepair::findOne($id);
    if (!$taskRepair) {
      return Re::data(null, '抢修订单信息读取失败', Re::ERROR);
    }
    $taskRepair->state = 4;
    $taskRepair->save();
    return Re::data();
  }

  public function actionAssignTaskRepair(){
    $id = Yii::$app->request->post('id', 0);
    $repair_user_id = Yii::$app->request->post('repair_user_id', 0);
    $task_info = Task::findOne($id);
    if (!$task_info) {
      return Re::data(null, '任务信息读取失败', Re::ERROR);
    }
    $user_info = User::findOne($repair_user_id);
    if (!$user_info) {
      return Re::data(null, '抢修员信息读取失败', Re::ERROR);
    }
    $taskRepair = new TaskRepair();
    $taskRepair->task_id = $id;
    $taskRepair->repair_id = $user_info->repair_id;
    $taskRepair->user_id = $repair_user_id;
    $taskRepair->admin_assign = 1;
    $taskRepair->state = 1;
    $taskRepair->status = 1;
    $taskRepair->created_at = time();
    $taskRepair->save();
    $task_info->state = 1;
    $task_info->save();
    $extra = [
      'push_type' => 'qxpd',
      'push_user_type' => 2
    ];
    JPushHelper::pushNotifyByReg((string)$repair_user_id, '派单通知', '有新的抢修单派单，请至后台查看', $extra);
    return Re::data();
  }

  public function actionChangeRepairUser(){
    $id = Yii::$app->request->post('id', 0);
    $user_id = Yii::$app->request->post('repair_user_id', 0);
    $taskRepair = TaskRepair::findOne($id);
    if (!$taskRepair) {
      return Re::data(null, '抢修订单信息读取失败', Re::ERROR);
    }
    $user = User::findOne($user_id);
    if (!$user) {
      return Re::data(null, '抢修人员信息读取失败', Re::ERROR);
    }
    $taskRepair->repair_id = $user->repair_id;
    $taskRepair->user_id = $user_id;
    $taskRepair->state = 1;
    $taskRepair->save();
    return Re::data();
  }

  public function actionRepairUserListForSelect(){
      $repair_user_id = Yii::$app->request->post('repair_user_id', 0);
      $list = User::find()->where(['status' => 1])->andWhere("repair_id <> 0 and id <> '$repair_user_id'")->all();
      $user_data = [];
      if ($list) {
        foreach ($list as $v) {
          $user_data[] = [
            'id' => $v->id,
            'name' => $v->phone.'('.$v->repair->name.')'
          ];
        }
      }
      return Re::data(['data' => $user_data]);
  }

  public function actionTaskRepairDetail(){
    $id = Yii::$app->request->post('id', 0);
    $task_repair = TaskRepair::findOne($id);
    $repairEvaluate = RepairEvaluate::find()->where(['task_id' => $task_repair->task_id])->one();
    $task_info = $task_repair->task;
    $gz_data = [];
    if ($task_info->gz_type_ids) {
      $gz_type_arr = explode(',', $task_info->gz_type_ids);
      foreach ($gz_type_arr as $v) {
        $device = Device::findOne($v);
        array_push($gz_data, $device->name);
      }
    }
    $task_data = [
      'repair_id' => $task_repair ? $task_repair->repair_id : 0,
      'repair_user_name' => $task_repair ? $task_repair->user->name : '',
      'repair_user_phone' => $task_repair ? $task_repair->user->phone : '',
      'repair_name' => $task_repair ? $task_repair->repair->name : '',
      'repair_user_longitude' => $task_repair ? $task_repair->lng : '',
      'repair_user_latitude' => $task_repair ? $task_repair->lat : '',
      'repair_start_content' => $task_repair ? $task_repair->start_content : '',
      'repair_start_imgs' => ($task_repair && $task_repair->start_imgs) ? explode(',', $task_repair->start_imgs) : [],
      'repair_finsh_content' => $task_repair ? $task_repair->finsh_content : '',
      'repair_finsh_imgs' => ($task_repair && $task_repair->finsh_imgs) ? explode(',', $task_repair->finsh_imgs) : [],
      'repair_finsh_time' => ($task_repair && $task_repair->finsh_at) ? date('Y-m-d H:i', $task_repair->finsh_at) : '',
      'repair_evaluate_star_finsh_time' => $repairEvaluate ? $repairEvaluate->star_finsh_time : '',
      'repair_evaluate_star_finsh_quality' => $repairEvaluate ? $repairEvaluate->star_finsh_quality : '',
      'repair_evaluate_star_service' => $repairEvaluate ? $repairEvaluate->star_service : '',
      'repair_evaluate_content' => $repairEvaluate ? $repairEvaluate->content : '',
      'repair_evaluate_time' => $repairEvaluate ? date('Y-m-d H:i', $repairEvaluate->created_at) : '',
      'repair_state' => $task_repair ? $task_repair->state : 0,
      'repair_state_name' => $task_repair ? $this->repair_state_arr[$task_repair->state] : '',
      'user_name' => $task_info->user->name ? $task_info->user->name : '',
      'user_phone' => $task_info->user->phone ? $task_info->user->phone : '',
      'task_longitude' => $task_info->lng,
      'task_latitude' => $task_info->lat,
      'task_state' => $task_info->state,
      'task_state_name' => $this->task_state_arr[$task_info->state],
      'task_device_main_name' => $task_info->deviceMain->name,
      'task_device_name' => $task_info->device->name,
      'task_gz_name' => $gz_data,
      'task_content' => $task_info->content,
      'task_is_need_bd' => $task_info->is_need_bd,
      'task_imgs' => $task_info->imgs ? explode(',', $task_info->imgs) : [],
      'task_area' => $task_info->province.$task_info->city.$task_info->area,
      'task_address' => $task_info->address,
      'address_detail' => $task_info->address_detail,
      'cost' => $task_repair ? $task_repair->cost : '',
    ];
    return Re::data(['data' => $task_data]);
  }

  public function actionRepairUserListForAssign(){
    $task_id = Yii::$app->request->post('task_id', '');
    $task_info = Task::findOne($task_id);
    if (!$task_info) {
      return Re::data(null, '任务信息读取失败', Re::ERROR);
    }
    $area_info = Area::find()->where(['level' => 2])->andWhere(['like', 'name', $task_info->area])->one();
    $repair_list = Repair::find()->where(['area_id' => $area_info->id, 'type' => [1,3], 'status' => 1])->orderBy('star_avg desc')->all();
    $repair_data = [];
    if ($repair_list) {
      foreach ($repair_list as $v) {
        $user_data = [];
        $user_list = User::find()->where(['repair_id' => $v->id])->all();
        if ($user_list) {
          foreach ($user_list as $v1) {
            $user_data[] = [
              'value' => $v1->id,
              'label' => $v1->name ? $v1->name : $v1->phone,
            ];
          }
        }
        $repair_data[] = [
          'value' => $v->id,
          'label' => $v->name,
          'children' => $user_data
        ];
      }
    }
    return Re::data(['data' => $repair_data]);
  }
}
